package com.xjtu.se.homework.ops.result.controller;

import com.xjtu.se.homework.common.Constants;
import com.xjtu.se.homework.common.Result;
import com.xjtu.se.homework.ops.result.service.ResultService;
import com.xjtu.se.homework.ops.result.dto.SearchDto;
import com.xjtu.se.homework.ops.result.bean.ResultContent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

@RestController
@RequestMapping("/ops/result")
public class ResultAPI {
    @Resource
    private ResultService resultService;

    @PostMapping("/getContent")
    public Result getContent(@RequestBody SearchDto dto, HttpServletResponse response) {
        ArrayList<ResultContent> list = resultService.getContent(dto); // 只有一条
        ResultContent resultContent = new ResultContent();
        if (list.size() != 0) {
            resultContent = list.get(0);

        }
        String items = resultContent.getItems();
        if (resultContent.getSearch_image() != null) {
            String search_image = resultContent.getSearch_image();
            FileInputStream in = null;
            OutputStream out = null;
            try {
                File file = new File(search_image);
                if (!file.exists()) {
                    throw new Exception("图片不存在");
                }
                in = new FileInputStream(search_image);
                int i = in.available();
                byte[] buffer = new byte[i];
                in.read(buffer);
                //设置输出流内容格式为图片格式
                response.setContentType("image/jpeg");
                //response的响应的编码方式为utf-8
                response.setCharacterEncoding("utf-8");
                out = response.getOutputStream();
                out.write(buffer);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return Result.success("success", items);
    }
}
